//
//  WCNPatientVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/15.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNPatientVC.h"
#import "WCNCareRecordVC.h"
#import "WCNPatientAddVC.h"

#import "WCNParentCareRecordVC.h"
//
#import "WCButton.h"
//
#import "WCNPatientClassTHFV.h"
#import "WCNPatientHospitalTCell.h"
#import "WCNPatientHomeTCell.h"
#import "MJRefresh.h"
//
#import "UINavigationItem+Offset.h"
#import "NSString+Utilities.h"
//
#import "WCDefaultManager.h"
#import "WCNetworkAccessManager.h"
#import "WCCoreDataStore.h"
//
#import "Constants.h"
#import "Macros.h"
#import "PopViewLikeQQView.h"
#import "WCNNewPICCPreserveVC.h"
#import "WCNPICCPreserveRecordAddVC.h"

#import "WCNNewPICCExtubationRecordVC.h"
#import "WCNWoundRecordVC.h"
#import <YTXAnimations/UIView+YTXAnimateCSS.h>
#import "XHDemoWeChatMessageTableViewController.h"
#import "XHMessageRootViewController.h"


static NSString *cellId1 = @"WCNPatientHospitalTCell";
static NSString *cellid2 = @"WCNPatientHomeTCell";
static NSString *headerId = @"WCNPatientClassTHFV";

@interface WCNPatientVC ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *patients;
@property (strong, nonatomic) NSString *url;
@property (assign, nonatomic) BOOL willRefresh;
@end

@implementation WCNPatientVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"伤口患者";
        _willRefresh = YES;
        self.navigationItem.titleView = [self customTitleView];
        _patients = [NSMutableArray array];
        defineWeakSelf;
        [[NSNotificationCenter defaultCenter] addObserverForName:PatientsRefreshNotification object:nil queue:nil usingBlock:^(NSNotification *note){
            weakSelf.willRefresh = YES;
//            if (![self.tableView.header isRefreshing]) {
//                [self refreshPatients];
//            }
        }];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    

    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:cellId1 bundle:nil] forCellReuseIdentifier:cellId1];
    [self.tableView registerNib:[UINib nibWithNibName:cellid2 bundle:nil] forCellReuseIdentifier:cellid2];
    [self.tableView registerClass:[WCNPatientClassTHFV class] forHeaderFooterViewReuseIdentifier:headerId];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf refreshPatients];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView.footer noticeNoMoreData];
    }];
    [self footerAddBtnWith:@"添加患者"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    UIButton *footerBtn =[self.view viewWithTag:900];
    [footerBtn ytx_bounceAnimtionWithDurationTime:1.0f];
    
    Account *account = [[WCDefaultManager shareMg] account];
    self.url = [NSString stringWithFormat:@"nursing/record/list/active/%@", account.stringId];
    if (self.willRefresh && ![self.tableView.header isRefreshing]) {
        [self refreshPatients];
    }
    //从数据库中取到数据源
    [self dealPatients:[[WCCoreDataStore shareStore] getPatients]];
}

- (UIView *)getNoInfoWarmView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 250)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 62, 62)];
    imageView.image = [UIImage imageNamed:@"Patient_No"];
    imageView.center = view.center;
    [view addSubview:imageView];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-60, 60)];
    label.center = CGPointMake(view.center.x, view.frame.size.height-label.frame.size.height/2);
    label.numberOfLines = 0;
    label.text = @"您尚未添加患者，请添加患者";
//    label.attributedText = [@"您尚未添加患者，请添加患者" noInfoAttributedStringWithIcon:@"Button_add" insertPosition:12];
    [view addSubview:label];
    return view;
}

#pragma mark -获取数据
- (void)refreshPatients
{
    [self refreshing:YES];
    [[WCNetworkAccessManager sharedMg] GET:self.url parameters:nil success:^(NSDictionary *result){
        [self dealPatients:[[WCCoreDataStore shareStore] createPatients:result[@"data"]]];
        if (self.patients.count > 0) {
            self.tableView.tableHeaderView = nil;
        } else {
            self.tableView.tableHeaderView = [self getNoInfoWarmView];
        }
       
    } failure:nil netError:nil always:^{
        [self.tableView.header endRefreshing];
        [self refreshing:NO];
        self.willRefresh = NO;
    }];
}
- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)dealPatients:(NSArray *)data
{
    NSMutableArray *array1 = [NSMutableArray array];
    NSMutableArray *array2 = [NSMutableArray array];
    NSMutableArray *array3 = [NSMutableArray array];
    
    for (Patient *patient in data) {
        NSString *type = patient.nursingType;
        if ([@"RESIDENT_PATIENT" isEqualToString:type]) {
            [array1 addObject:patient];
        } else if ([@"FAMILY_PATIENT" isEqualToString:type]) {
            [array2 addObject:patient];
        } else if ([@"OUT_PATIENT" isEqualToString:type]) {
            [array3 addObject:patient];
        }
    }
    
    [self.patients removeAllObjects];
    //组合统一病区的护理对象
    if (array1.count > 0) {
        int i = 0;
        Patient *patient = array1[i]; [array1 removeObjectAtIndex:i];
        //住院 分为两个科 用
        NSMutableArray *array3 = [NSMutableArray arrayWithObjects:patient, nil];
        while (true) {
            if (i == array1.count && array1.count != 0) {
                [self.patients addObject:array3];
                i = 0;
                patient = array1[i]; [array1 removeObjectAtIndex:i];
                array3 = [NSMutableArray arrayWithObjects:patient, nil];
            }
            
            if (array1.count == 0) {
                [self.patients addObject:array3];
                break;
            }
            
            Patient *patientNext = array1[i];
            if ([patient.hosWardName isEqualToString:patientNext.hosWardName]) {
                [array3 addObject:patientNext];
                [array1 removeObjectAtIndex:i];
            } else {
                i++;
            }
        }
    }
    
    if (array2.count > 0) {
        [self.patients addObject:array2];
    }
    if (array3.count > 0) {
        [self.patients addObject:array3];
    }
 [self.tableView reloadData];
}

- (void)footerAddBtnClick
{
    WCNPatientAddVC *vc = [[WCNPatientAddVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.patients.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *patientArray = self.patients[section];
    return patientArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Patient *patient = self.patients[indexPath.section][indexPath.row];
    if ([@"RESIDENT_PATIENT" isEqualToString:patient.nursingType]) {
        WCNPatientHospitalTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId1 forIndexPath:indexPath];
        [cell setBedNoText:patient.hosBedNo];
        [cell setLevelText:patient.nursingLevel];
        cell.name.text = patient.name;
        [cell setPartText:patient.woundDesc];
        [cell setStatus:patient.nursingStatus text:patient.nursingStatusName];
        return cell;
    } else if ([@"FAMILY_PATIENT" isEqualToString:patient.nursingType] | [@"OUT_PATIENT" isEqualToString:patient.nursingType]) {
        WCNPatientHomeTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid2 forIndexPath:indexPath];
        cell.name.text = patient.name;
        [cell setLevelText:patient.nursingLevel];
        [cell setPartText:patient.woundDesc];
        NSLog(@"age:%@",patient.age);
        cell.address.text = patient.age;
        [cell setStatus:patient.nursingStatus text:patient.nursingStatusName];
        return cell;
    }
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    WCNPatientClassTHFV *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
    Patient *patient = self.patients[section][0];
    if ([@"RESIDENT_PATIENT" isEqualToString:patient.nursingType]) {
        header.titleLabel.text = [NSString stringWithFormat:@"住院-%@", patient.hosWardName];
    } else if ([@"FAMILY_PATIENT" isEqualToString:patient.nursingType]) {
        header.titleLabel.text = @"家庭病床";
    }else if ([@"OUT_PATIENT" isEqualToString:patient.nursingType]) {
        header.titleLabel.text = @"门诊病人";
    }
    return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

  //  /*
//     Patient *patient = self.patients[indexPath.section][indexPath.row];
//     NSLog(@"%@",patient.stringId);
//     WCNWoundRecordVC *vc = [[WCNWoundRecordVC alloc] initWithTitle:patient mode:WCNCareRecordVCModeEdit];
//     [self.navigationController pushViewController:vc animated:YES];
    //*/

    
     Patient *patient = self.patients[indexPath.section][indexPath.row];
     NSLog(@"%@",patient.stringId);
     WCNWoundRecordVC *vc = [[WCNWoundRecordVC alloc] initWithTitle:patient mode:WCNCareRecordVCModeEdit];
     [self.navigationController pushViewController:vc animated:YES];
    
    
    
    
   
     
    
}

@end
